<template>
  <el-drawer
    v-model="drawerVisible"
    class="jiankang-drawer"
    :size="size"
    :close-on-click-modal="false"
    destroy-on-close
  >
    <template #header>
      <div class="flex justify-between mr-2">
        <div class="text-black font-bold">{{ title }}</div>
        <LangSwitch :model-value="currentLang" @change="handleLanguageChange" />
      </div>
    </template>

    <div class="drawer-content">
      <!-- 饮食建议 -->
      <!-- 循环 dietSuggestionsArr，分别渲染“饮食运动建议”和“生活习惯建议” -->
      <div class="section">
        <div class="flex justify-between">
          <!-- 名字为2显示“饮食运动建议”，3显示“生活习惯建议” -->
          <div class="section-title">饮食运动建议</div>
          <div
            class="text-blue-400 text-xs cursor-pointer"
            @click="() => openDialogVisible(2)"
          >
            历史记录
          </div>
        </div>

        <!-- AI 建议 -->
        <div v-if="dietSuggestions.length > 0" class="sub-section">
          <div class="sub-title">AI 建议</div>
          <div
            v-for="item in dietSuggestions"
            :key="item.suggestionId"
            class="suggestion-item"
          >
            <div class="suggestion-content">
              <!-- <div>{{ item.aiTitle || "AI智能分析" }}</div> -->
              <div>{{ item.content || "暂无AI建议" }}</div>
            </div>
            <el-button type="primary" link @click="quoteAISuggestion(item)">
              引用
            </el-button>
          </div>
        </div>

        <!-- 医生建议 -->
        <div class="sub-section">
          <div class="sub-title">医生建议</div>
          <el-input
            v-model="doctorSuggestion"
            type="textarea"
            :rows="4"
            placeholder="请输入医生建议"
          />
        </div>
      </div>

      <!-- 健康建议 -->
      <div class="section">
        <div class="flex justify-between">
          <!-- 名字为2显示“饮食运动建议”，3显示“生活习惯建议” -->
          <div class="section-title">生活习惯建议</div>
          <div
            class="text-blue-400 text-xs cursor-pointer"
            @click="() => openDialogVisible(3)"
          >
            历史记录
          </div>
        </div>

        <!-- AI 建议 -->
        <div v-if="habitSuggestions.length > 0" class="sub-section">
          <div class="sub-title">AI 建议</div>
          <div
            v-for="item in habitSuggestions"
            :key="item.suggestionId"
            class="suggestion-item"
          >
            <div class="suggestion-content">
              <!-- <div>{{ item.aiTitle || "AI智能分析" }}</div> -->
              <div>{{ item.content || "暂无AI建议" }}</div>
            </div>
            <el-button type="primary" link @click="quoteAISuggestion(item)">
              引用
            </el-button>
          </div>
        </div>

        <!-- 医生建议 -->
        <div class="sub-section">
          <div class="sub-title">医生建议</div>
          <el-input
            v-model="doctorHealthSuggestion"
            type="textarea"
            :rows="4"
            placeholder="请输入医生建议"
          />
        </div>
      </div>

      <!-- 用药建议 -->
      <div class="section">
        <div class="flex justify-between">
          <!-- 名字为2显示“饮食运动建议”，3显示“生活习惯建议” -->
          <div class="section-title">用药建议</div>
          <div
            class="text-blue-400 text-xs cursor-pointer"
            @click="() => openDialogVisible(4)"
          >
            历史记录
          </div>
        </div>
        <el-table :data="medicationList" border>
          <el-table-column
            prop="drugName"
            :label="t('healthRecords.healthInfo.medicationTable.drugName')"
            width="200"
          >
            <template #default="{ row }">
              <el-input
                v-model="row.drugName"
                :placeholder="
                  t('healthRecords.healthInfo.placeholders.enterDrugName')
                "
                class="borderless-input"
              />
            </template>
          </el-table-column>
          <el-table-column
            prop="usageMethod"
            :label="t('healthRecords.healthInfo.medicationTable.usageMethod')"
            width="200"
          >
            <template #default="{ row }">
              <el-input
                v-model="row.usageMethod"
                :placeholder="
                  t('healthRecords.healthInfo.placeholders.enterUsage')
                "
                class="borderless-input"
              />
            </template>
          </el-table-column>
          <el-table-column
            prop="doseQuantity"
            :label="t('healthRecords.healthInfo.medicationTable.doseQuantity')"
            width="200"
          >
            <template #default="{ row }">
              <el-input
                v-model="row.doseQuantity"
                :placeholder="
                  t('healthRecords.healthInfo.placeholders.enterDose')
                "
                class="borderless-input"
              />
            </template>
          </el-table-column>
          <el-table-column
            prop="frequency"
            :label="t('healthRecords.healthInfo.medicationTable.doseUnit')"
            width="200"
          >
            <template #default="{ row }">
              <el-input
                v-model="row.doseUnit"
                :placeholder="
                  t('healthRecords.healthInfo.medicationTable.doseUnit')
                "
                class="borderless-input"
              />
            </template>
          </el-table-column>
          <el-table-column
            prop="frequency"
            :label="t('healthRecords.healthInfo.medicationTable.frequency')"
            width="200"
          >
            <template #default="{ row }">
              <el-input
                v-model="row.frequency"
                :placeholder="
                  t('healthRecords.healthInfo.placeholders.enterFrequency')
                "
                class="borderless-input"
              />
            </template>
          </el-table-column>
          <el-table-column
            prop="timing"
            :label="t('healthRecords.healthInfo.medicationTable.timing')"
            width="200"
          >
            <template #default="{ row }">
              <el-input
                v-model="row.timing"
                :placeholder="
                  t('healthRecords.healthInfo.placeholders.enterTiming')
                "
                class="borderless-input"
              />
            </template>
          </el-table-column>
          <el-table-column
            prop="treatment"
            :label="t('healthRecords.healthInfo.medicationTable.treatment')"
            width="200"
          >
            <template #default="{ row }">
              <el-input
                v-model="row.treatment"
                :placeholder="
                  t('healthRecords.healthInfo.placeholders.enterTreatment')
                "
                class="borderless-input"
              />
            </template>
          </el-table-column>
          <el-table-column
            prop="startDate"
            :label="t('healthRecords.healthInfo.medicationTable.startDate')"
            width="200"
          >
            <template #default="{ row, $index }">
              <el-input
                v-model="row.startDate"
                readonly
                :placeholder="
                  t('healthRecords.healthInfo.placeholders.startDate')
                "
                class="borderless-input date-input-field"
                @click="handleOpenDatePicker($index)"
              >
                <template #suffix>
                  <el-icon
                    class="cursor-pointer text-gray-400 hover:text-blue-500"
                  >
                    <Calendar />
                  </el-icon>
                </template>
              </el-input>
            </template>
          </el-table-column>
          <el-table-column
            :label="t('healthRecords.healthInfo.medicationTable.actions')"
            fixed="right"
          >
            <template #default="{ $index }">
              <el-button type="danger" link @click="deleteMedication($index)">
                <el-icon><Delete /></el-icon>
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="add-medication">
          <el-button link @click="addMedication">
            <el-icon><Plus /></el-icon>添加
          </el-button>
        </div>
      </div>
    </div>

    <!-- 底部操作按钮 -->
    <template #footer>
      <div class="drawer-footer">
        <el-button @click="handleSave(1)">保存草稿</el-button>
        <el-button type="primary" @click="handleSave(2)">提交</el-button>
      </div>
    </template>

    <el-dialog v-model="dialogVisible" title="历史记录" width="500">
      <el-timeline style="max-width: 600px">
        <el-timeline-item
          v-for="item in dialogDetailList"
          :key="item.dataId"
          :timestamp="item.createTime"
          placement="top"
        >
          <el-card>
            <h4>{{ item.userName }}</h4>

            <el-table v-if="item.type === 4" :data="item.content" border>
              <el-table-column
                prop="drugName"
                :label="t('healthRecords.healthInfo.medicationTable.drugName')"
                width="200"
              >
                <template #default="{ row }">
                  {{ row.drugName }}
                </template>
              </el-table-column>
              <el-table-column
                prop="usageMethod"
                :label="
                  t('healthRecords.healthInfo.medicationTable.usageMethod')
                "
                width="200"
              >
                <template #default="{ row }">
                  {{ row.usageMethod }}
                </template>
              </el-table-column>
              <el-table-column
                prop="doseQuantity"
                :label="
                  t('healthRecords.healthInfo.medicationTable.doseQuantity')
                "
                width="200"
              >
                <template #default="{ row }">
                  {{ row.doseQuantity }}
                </template>
              </el-table-column>
              <el-table-column
                prop="frequency"
                :label="t('healthRecords.healthInfo.medicationTable.doseUnit')"
                width="200"
              >
                <template #default="{ row }">
                  {{ row.doseUnit }}
                </template>
              </el-table-column>
              <el-table-column
                prop="frequency"
                :label="t('healthRecords.healthInfo.medicationTable.frequency')"
                width="200"
              >
                <template #default="{ row }">
                  {{ row.frequency }}
                </template>
              </el-table-column>
              <el-table-column
                prop="timing"
                :label="t('healthRecords.healthInfo.medicationTable.timing')"
                width="200"
              >
                <template #default="{ row }">
                  {{ row.timing }}
                </template>
              </el-table-column>
              <el-table-column
                prop="treatment"
                :label="t('healthRecords.healthInfo.medicationTable.treatment')"
                width="200"
              >
                <template #default="{ row }">
                  {{ row.treatment }}
                </template>
              </el-table-column>
              <el-table-column
                prop="treatment"
                :label="t('healthRecords.healthInfo.placeholders.startDate')"
                width="200"
              >
                <template #default="{ row }">
                  {{ row.startDate }}
                </template>
              </el-table-column>
            </el-table>
            <p v-else v-for="(contentItem, index) in item.content" :key="index">
              {{ contentItem }}
            </p>
          </el-card>
        </el-timeline-item>
      </el-timeline>
      <template #footer>
        <div class="dialog-footer">
          <el-button
            type="primary"
            plain
            size="small"
            @click="dialogVisible = false"
          >
            关闭
          </el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog
      v-model="showDatePicker"
      width="400px"
      :close-on-click-modal="false"
      :close-on-press-escape="true"
      destroy-on-close
      center
      :title="'选择用药开始时间'"
      class="no-header-dialog"
    >
      <div class="date-picker-content">
        <el-date-picker
          v-model="tempDate"
          type="date"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          class="w-full"
          :clearable="true"
          :editable="false"
        />
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleConfirmDatePicker">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>
  </el-drawer>
</template>

<script lang="ts" setup>
import { reportApi } from "@/api/report-api";
import LangSwitch from "@/components/LangSwitch/index.vue";
import { Calendar, Delete, Plus } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import { defineEmits, defineExpose, defineProps, ref } from "vue";
import { useI18n } from "vue-i18n";
// 国际化
const { t, locale } = useI18n();

// 定义属性
const props = defineProps({
  title: {
    type: String,
    default: "健康建议"
  },
  size: {
    type: String,
    default: "600px"
  }
});

// 定义事件
const emit = defineEmits(["update:modelValue", "save"]);

// 抽屉显示状态
const drawerVisible = ref(false);
const dialogVisible = ref(false);
const reportId = ref(0);
// 医生建议内容
const doctorSuggestion = ref("");
const doctorHealthSuggestion = ref("");

// 用药列表
const medicationList = ref([]);
console.log("medicationList初始化:", medicationList.value);

const dietSuggestions = ref([]);
const habitSuggestions = ref([]);
const dialogDetailList = ref([]);

// 时间选择器弹窗相关状态
const showDatePicker = ref(false); // 控制日期选择器弹窗显示
const currentEditingIndex = ref(-1); // 当前正在编辑的用药记录索引
const tempDate = ref(""); // 临时保存选择的日期

const currentLang = ref("zh");

const handleLanguageChange = (lang: string) => {
  console.log("语言切换为:", lang);
  currentLang.value = lang;

  handleHealthSuggestion(reportId.value);
};

const openDialogVisible = async id => {
  const res = await reportApi.getTracerInfo({
    type: id,
    pageNum: 1,
    pageSize: 10,
    dataId: reportId.value
  });
  let { list } = res.data;
  dialogDetailList.value = list;
  dialogVisible.value = true;
};
// 引用AI建议时，只保留最新一次的引用内容，覆盖原有内容
const quoteAISuggestion = item => {
  console.log("引用AI建议：", item);
  // 根据建议类型判断覆盖到哪个输入框
  if (item.type === 2) {
    // 饮食运动建议
    doctorSuggestion.value = item.content || "";
  } else if (item.type === 3) {
    // 生活习惯建议
    doctorHealthSuggestion.value = item.content || "";
  }
};

// 添加用药
const addMedication = () => {
  medicationList.value.push({
    drugName: "",
    usageMethod: "",
    doseQuantity: "",
    frequency: "",
    timing: "",
    doseUnit: "",
    startDate: "",
    treatment: "",
    dataType: 1,
    dataId: Number(reportId.value)
  });
};

// 删除用药
const deleteMedication = (index: number) => {
  medicationList.value.splice(index, 1);
};

// 关闭抽屉
const closeDrawer = () => {
  drawerVisible.value = false;
  emit("update:modelValue", false);
};

// 保存操作
const handleSave = saveType => {
  // 整理所有建议数据
  const details = [];

  // 添加饮食运动建议
  if (doctorSuggestion.value) {
    details.push({
      type: 2,
      content: doctorSuggestion.value,
      referenceId: dietSuggestions.value?.[0]?.referenceId // 如果有引用AI建议，记录其ID
    });
  }

  // 添加生活习惯建议
  if (doctorHealthSuggestion.value) {
    details.push({
      type: 3,
      content: doctorHealthSuggestion.value,
      referenceId: habitSuggestions.value?.[0]?.referenceId // 如果有引用AI建议，记录其ID
    });
  }
  console.log("保存前的用药数据:", medicationList.value);

  // 处理用药数据，将 startDate 转换为毫秒级时间戳
  const processedMedications = medicationList.value.map(medication => ({
    ...medication,
    // 将 startDate 转换为毫秒级时间戳，如果没有日期则为空字符串
    startDate: medication.startDate
      ? new Date(medication.startDate).getTime()
      : ""
  }));

  console.log("处理后的用药数据:", processedMedications);

  const data = {
    id: Number(reportId.value), // TODO: 这里需要使用实际的reportId
    saveType: saveType, // 1: 草稿, 2: 提交
    type: 1,
    requestSource: 3, //1-健康档案、2-随访计划、3-检查报告
    healthSuggestions: details,
    medications: processedMedications
  };

  // 调用保存接口
  reportApi
    .healthSuggestionSave(data)
    .then(res => {
      console.log("保存结果：", res);
      if (res.code === 0) {
        ElMessage.success(saveType === 1 ? "保存草稿成功" : "提交成功");
        closeDrawer();
      } else {
        ElMessage.error(res.message || "保存失败");
      }
    })
    .catch(err => {
      console.error("保存失败：", err);
      ElMessage.error("保存失败，请重试");
    });
};

const handleHealthSuggestion = async reportId => {
  const params = {
    id: reportId,
    type: 1
  };

  const res = await reportApi.healthSuggestionApi(params);

  let { medications, healthSuggestions, ...rest } = res.data;

  // 确保medications是一个数组
  if (!Array.isArray(medications)) {
    medications = [];
  }

  // 处理medications中的时间戳，转换为日期格式用于显示
  medicationList.value = medications.map(medication => ({
    ...medication,
    // 如果startDate是时间戳，转换为YYYY-MM-DD格式
    startDate:
      medication.startDate && !isNaN(Number(medication.startDate))
        ? new Date(Number(medication.startDate)).toISOString().split("T")[0]
        : medication.startDate
  }));

  // 先按照type 2：饮食运动建议 3：生活习惯建议 分为两组 然后后价格字段name 分别为饮食运动建议 生活习惯建议
  let dietSuggestionsArr = healthSuggestions?.filter(item => item.type === 2);
  let habitSuggestionsArr = healthSuggestions?.filter(item => item.type === 3);

  dietSuggestions.value = dietSuggestionsArr?.filter(item => item.ai);
  habitSuggestions.value = habitSuggestionsArr?.filter(item => item.ai);
  doctorSuggestion.value = dietSuggestionsArr
    ?.filter(item => !item.ai)
    .map(item => item.content)
    .join(",");

  doctorHealthSuggestion.value = habitSuggestionsArr
    ?.filter(item => !item.ai)
    .map(item => item.content)
    .join(",");
};
// 打开日期选择器弹窗
const handleOpenDatePicker = (index: number) => {
  console.log("打开日期选择器弹窗", {
    用药记录索引: index,
    当前开始时间: medicationList.value[index]?.startDate
  });

  currentEditingIndex.value = index;
  tempDate.value = medicationList.value[index]?.startDate || "";
  showDatePicker.value = true;
};

// 确认日期选择
const handleConfirmDatePicker = () => {
  if (currentEditingIndex.value < 0 || !medicationList.value) {
    console.error("确认日期时出错：无效的编辑索引");
    ElMessage.error("操作失败：无效的用药记录");
    return;
  }

  const originalDate =
    medicationList.value[currentEditingIndex.value]?.startDate;

  console.log("确认日期选择", {
    编辑索引: currentEditingIndex.value,
    原始日期: originalDate,
    新选择日期: tempDate.value
  });

  // 更新用药记录的开始时间
  if (medicationList.value[currentEditingIndex.value]) {
    medicationList.value[currentEditingIndex.value].startDate = tempDate.value;

    console.log("日期更新成功", {
      更新后的日期: medicationList.value[currentEditingIndex.value].startDate,
      用药记录: medicationList.value[currentEditingIndex.value]
    });
  }

  // 关闭弹窗并重置状态
  showDatePicker.value = false;
  currentEditingIndex.value = -1;
  tempDate.value = "";
};
// 对外暴露的方法
defineExpose({
  // 打开抽屉的方法
  open(reportId1) {
    drawerVisible.value = true;
    handleHealthSuggestion(reportId1);
    reportId.value = reportId1;
  }
});
</script>

<style lang="scss">
.jiankang-drawer {
  .el-drawer__header {
    padding: 20px 24px !important;
    border-bottom: 1px solid #f0f0f0 !important;
    margin-bottom: 0 !important;
    background-color: #fff !important;
  }

  .el-drawer__title {
    font-size: 16px !important;
    font-weight: 600 !important;
    color: #333 !important;
  }
  .section {
    margin-bottom: 24px;

    .section-title {
      font-size: 16px;
      font-weight: 500;
      color: #333;
      margin-bottom: 16px;
      padding-left: 8px;
      border-left: 4px solid #409eff;
    }

    .sub-section {
      margin-bottom: 16px;

      .sub-title {
        font-size: 14px;
        color: #666;
        margin-bottom: 12px;
      }
    }
  }

  .suggestion-item {
    display: flex;
    align-items: flex-start;
    justify-content: space-between;
    background-color: #f8f9fa;
    padding: 12px;
    border-radius: 4px;
    margin-bottom: 12px;

    .suggestion-content {
      flex: 1;

      div {
        &:first-child {
          font-weight: 500;
          margin-bottom: 4px;
        }

        &:last-child {
          color: #666;
          font-size: 14px;
        }
      }
    }
  }

  .add-medication {
    margin-top: 12px;
    display: flex;
    width: 68px;
    height: 28px;
    background: #ffffff;
    border-radius: 2px;
    border: 1px solid #d6d6d6;
    color: #333;
    flex-wrap: nowrap;
    flex-direction: row;
    justify-content: center;
    align-items: center;
  }

  .el-table {
    margin-top: 12px;

    .el-button {
      padding: 4px 0;
    }
  }

  .drawer-footer {
    text-align: right;
    padding: 0 20px 20px;
  }
}

// 日期输入框样式
:deep(.date-input-field) {
  .el-input__wrapper {
    cursor: pointer;

    &:hover {
      box-shadow: 0 0 0 1px
        var(--el-input-hover-border, var(--el-border-color-hover)) inset;
    }
  }

  .el-input__inner {
    cursor: pointer;
  }
}
.no-header-dialog {
  .el-dialog__body {
    text-align: center;
  }
}
</style>
